package com.dingwei.lesyndrome.mvp.presenter;

import android.app.Dialog;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.dingwei.lesyndrome.R;
import com.dingwei.lesyndrome.app.MyApplication;
import com.dingwei.lesyndrome.base.FailsBean;
import com.dingwei.lesyndrome.base.MyBaseBean;
import com.dingwei.lesyndrome.bean.GamCircleTypeBean;
import com.dingwei.lesyndrome.custom.myCallback;
import com.dingwei.lesyndrome.mvp.view.Contract;
import com.dingwei.lesyndrome.ui.activity.AddCircleActivity;
import com.dingwei.lesyndrome.utils.UploadVideoDialog;
import com.guoxiaoxing.phoenix.compress.video.VideoCompressor;
import com.guoxiaoxing.phoenix.compress.video.format.MediaFormatStrategyPresets;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.base.URLS;
import com.lihao.baselibrary.base.basePresenter;
import com.lihao.baselibrary.utils.ImageUtils;
import com.lihao.baselibrary.utils.L;
import com.lihao.baselibrary.weight.WheelView;
import com.luck.picture.lib.entity.LocalMedia;

import org.w3c.dom.Text;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lihao on 2017/9/12.
 */

public class AddCirclePresenter extends basePresenter {

    private Contract.AddCircleView addCircleView;
    private Dialog typeDialog;//分类弹出框

    public AddCirclePresenter(Contract.AddCircleView view) {
        super(view);
        this.addCircleView = view;
    }

    public void showChooseTypeDialog(AddCircleActivity activity, final GamCircleTypeBean typeBean) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < typeBean.data.size(); i++) {
            list.add(typeBean.data.get(i).name);
        }

        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.dialog_check_sex, null);
        TextView tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
        TextView tvSubmit = (TextView) view.findViewById(R.id.tv_submit);
        final WheelView wheelView = (WheelView) view.findViewById(R.id.wheel);
        wheelView.setOffset(2);
        wheelView.setItems(list);
        view.measure(0, 0);

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeDialog.dismiss();
            }
        });
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeDialog.dismiss();
                GamCircleTypeBean.DataBean data = typeBean.data.get(wheelView.getSeletedIndex());
                addCircleView.selectType(data);
            }
        });
        typeDialog = new Dialog(activity, R.style.Theme_Light_Dialog);
        typeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        typeDialog.setContentView(view);
        Window dialogWindow = typeDialog.getWindow();
        //设置dialog在屏幕底部
        dialogWindow.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        dialogWindow.setWindowAnimations(R.style.dialogstyle);
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        dialogWindow.setAttributes(lp);
        typeDialog.show();
    }

    public void commitVideo(String cid, String content, boolean open, final String videoPath, List<LocalMedia> photoList) {
        if (TextUtils.isEmpty(content)){
            showToast("请输入内容！");
            return;
        }
        final RequestParams rp = new RequestParams(URLS.HOST+URLS.PUBLISH_CIRCLE);
        rp.addBodyParameter("cid", cid);
        rp.addBodyParameter("content", content);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        if (open){
            rp.addBodyParameter("address", MyApplication.location.getCity()+ "·" + MyApplication.location.getStreet());
            rp.addBodyParameter("longitude",MyApplication.location.getLongitude()+"");
            rp.addBodyParameter("latitude",MyApplication.location.getLatitude()+"");
        }
        rp.addBodyParameter("cid", cid);

        if (!TextUtils.isEmpty(videoPath)){
            rp.addBodyParameter("vimg", ImageUtils.compressImage(ImageUtils.getVideoThumbnail(videoPath,300,150, MediaStore.Images.Thumbnails.MICRO_KIND)));
            final UploadVideoDialog prosDialog = new UploadVideoDialog(BaseActivity.context);
            prosDialog.show();
            prosDialog.setHint("正在压缩...");
            final File compressFile;
            try {
                File compressCachePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "phoenix");
                compressCachePath.mkdir();
                compressFile = File.createTempFile("compress", ".mp4", compressCachePath);
            } catch (IOException e) {
                showToast("Failed to create temporary file.");
                return;
            }
            try {
                VideoCompressor.with().asyncTranscodeVideo(videoPath, compressFile.getAbsolutePath(),
                        MediaFormatStrategyPresets.createAndroid480pFormatStrategy(), new VideoCompressor.Listener() {
                            @Override
                            public void onTranscodeProgress(double progress) {
                                L.e("progress =" + progress);
                                prosDialog.setProgress((int) (progress * 100));
                            }

                            @Override
                            public void onTranscodeCompleted() {
                                if (compressFile != null && compressFile.exists()) {
                                    L.e("size = " + compressFile.length());
                                    rp.addBodyParameter("video",compressFile);
                                    x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, false,rp) {
                                        @Override
                                        public void back(MyBaseBean baseBean, String result) {
                                            prosDialog.dismiss();
                                            addCircleView.submitSuccess();
                                        }

                                        @Override
                                        public void onLoading(long total, long current, boolean isUploading) {
                                            super.onLoading(total, current, isUploading);

                                            prosDialog.setProgress((int)(current/(total/100)));
                                            if ((int)(current/(total/100)) < 100) {
                                                prosDialog.setHint("正在上传...");
                                            } else {
                                                prosDialog.setHint("服务器处理中...");
                                            }
                                        }

                                        @Override
                                        public void fail(FailsBean baseBean, String result) {
                                            showToast(result);
                                            prosDialog.dismiss();
                                        }
                                    });
                                } else {
                                    return;
                                }

                            }

                            @Override
                            public void onTranscodeCanceled() {
                            }

                            @Override
                            public void onTranscodeFailed(Exception exception) {
                                File file = new File(videoPath);
                                if (file != null && file.exists()) {
                                    L.e("size = " + file.length());
                                    rp.addBodyParameter("video",file);
                                } else {
                                    return;
                                }

                                x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, false,rp) {
                                    @Override
                                    public void back(MyBaseBean baseBean, String result) {
                                        prosDialog.dismiss();
                                        addCircleView.submitSuccess();
                                    }

                                    @Override
                                    public void onLoading(long total, long current, boolean isUploading) {
                                        super.onLoading(total, current, isUploading);

                                        prosDialog.setProgress((int)(current/(total/100)));
                                        if ((int)(current/(total/100)) < 100) {
                                            prosDialog.setHint("正在上传...");
                                        } else {
                                            prosDialog.setHint("服务器处理中...");
                                        }
                                    }

                                    @Override
                                    public void fail(FailsBean baseBean, String result) {
                                        showToast(result);
                                        prosDialog.dismiss();
                                    }
                                });

                            }
                        });
            } catch (IOException e) {
                e.printStackTrace();
            }


        }else {
            for (int i = 1; i <= photoList.size(); i++) {
                if (!TextUtils.isEmpty(photoList.get(i-1).getCompressPath())){
                    rp.addBodyParameter("img_"+i,new File(photoList.get(i-1).getCompressPath()));
                }
            }

            x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, true,rp) {
                @Override
                public void back(MyBaseBean baseBean, String result) {
                    addCircleView.submitSuccess();
                }


                @Override
                public void fail(FailsBean baseBean, String result) {
                    showToast(result);
                }
            });
        }



    }
}
